package com.gaofans.vertx.boot.web.handler;

import java.util.*;

/**
 * handler调用链
 * @author GaoFans
 */
public class HttpHandlerChain {

    /**
     * 用户handler之前的
     */
    private final List<HttpHandlerDefinition> preHandlers;
    /**
     * 用户handler之后的
     */
    private final List<HttpHandlerDefinition> postHandlers;

    private boolean change = false;

    public HttpHandlerChain() {
        this.preHandlers = new ArrayList<>();
        this.postHandlers = new ArrayList<>();
    }

    synchronized void add(HttpHandlerDefinition definition){
        Objects.requireNonNull(definition);
        change = true;
        if(definition.getPosition().equals(HttpHandlerPosition.PRE)){
            this.preHandlers.add(definition);
        }else{
            this.postHandlers.add(definition);
        }
    }

    public synchronized List<HttpHandlerDefinition> getPreHandlers() {
        sort();
        return Collections.unmodifiableList(preHandlers);
    }

    public synchronized List<HttpHandlerDefinition> getPostHandlers() {
        sort();
        return Collections.unmodifiableList(postHandlers);
    }

    private void sort() {
        if (change) {
            preHandlers.sort(Comparator.comparingInt(HttpHandlerDefinition::getOrder));
            postHandlers.sort(Comparator.comparingInt(HttpHandlerDefinition::getOrder));
            change = false;
        }
    }

}
